﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Threading;

namespace RPGXEngine.Debugging
{
    public class Performance
    {
        #region Properties

        public double LastThreadTime
        {
            get { return _lastThreadTime; }
            set { _lastThreadTime = value; }
        }
        private double _lastThreadTime = 0d;

        public PerformanceCounter CPUCounter
        {
            get { return _cpuCounter; }
            set { _cpuCounter = value; }
        }
        private PerformanceCounter _cpuCounter = new PerformanceCounter("Process", "% Processor Time", "Idle");

        #endregion

        #region Public Methods

        public Performance()
        {
        }

        public void Init()
        {
            this.LastThreadTime = Process.GetCurrentProcess().TotalProcessorTime.TotalMilliseconds;

            this.CPUCounter.NextValue(); // let it get a good value next time
        }

        public PerformanceData Update(long refreshInterval)
        {
            PerformanceData data = new PerformanceData();

            Process currentProcess = Process.GetCurrentProcess();

            float currentCPUTime = (float)currentProcess.TotalProcessorTime.TotalMilliseconds;
            float idleProcessTime = this.CPUCounter.NextValue();

            float cpuTimeDelta = currentCPUTime - (float)this.LastThreadTime;

            data.BytesInUse = Process.GetCurrentProcess().PrivateMemorySize64;
            data.CPUUsage = 100.0f / Math.Abs(cpuTimeDelta / (100.0f - idleProcessTime));
            data.NumberOfThreads = currentProcess.Threads.Count;

            this.LastThreadTime = currentCPUTime;

            return data;
        }

        #endregion
    }
}
